package com.zg.common.core.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.common.core.dao.BaseDao;
import com.zg.common.core.dao.BaseEntity;

import com.zg.common.core.dao.IDao;
import com.zg.common.core.req.PageReq;
import com.zg.common.core.vo.BaseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/22 10:50
 */

@Slf4j
public abstract class PageBaseService<T extends BaseEntity,D extends IDao<T>> extends BaseService<T,D> implements IPageBaseService<T> {



    @Override
    public <V extends BaseVo> Page<V> page(PageReq req, Class<V> voClass) {
        Page<T> page = new Page<>(req.getPage(), req.getPageSize());

        // 2. 查询实体分页
        Page<T> pageInfo = pageInfo(page, req);

        // 3. 转换为VO列表（使用泛型方法）
        List<V> voList = pageInfo.getRecords().stream()
                .map(entity -> convertToVo(entity, voClass))
                .collect(Collectors.toList());

        // 4. 创建与voClass匹配的VO分页对象
        Page<V> voPage = new Page<>(pageInfo.getCurrent(), pageInfo.getSize(), pageInfo.getTotal());
        voPage.setRecords(voList);

        return voPage;
    }

    protected   Page<T> pageInfo(Page<T> page,PageReq req){
        LambdaQueryWrapper<T> qw = buildQueryWrapper(req);
        return baseDao.page(page, qw);
    }

    protected  LambdaQueryWrapper<T> buildQueryWrapper(PageReq req) {
        return  buildQueryWrapper(convertReqToEntity(req));
    }

    // 转换方法，子类可重写
    protected T convertReqToEntity(PageReq req) {
        if (req == null) return null;
        try {
            T entity = getEntityClass().getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(req, entity);
            return entity;
        } catch (Exception e) {
            log.error("转换失败: {}", e.getMessage(), e);
            return null;
        }
    }

    // 新增方法：获取当前泛型 T 的 Class 对象
    private Class<T> getEntityClass() {
        ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
        return (Class<T>) ptype.getActualTypeArguments()[0];
    }

    protected LambdaQueryWrapper<T> buildPageQueryWrapper(PageReq req){
        T t = convertReqToEntity(req);
        return  buildQueryWrapper(t);
    }


    protected <C extends BaseVo> C convertToVo(T entity, Class<C> targetClass) {
        if (entity == null) return null;

        try {
            C vo = targetClass.getDeclaredConstructor().newInstance();

            // 支持子类重写自定义转换逻辑
            customizeConversion(entity, vo);

            return vo;
        } catch (Exception e) {
            log.error("转换失败：{}", e.getMessage(), e);
            return null;
        }
    }

    // 钩子方法供子类扩展
    protected void customizeConversion(T entity, BaseVo vo) {
        BeanUtils.copyProperties(entity, vo);
    }
}
